using OfficeOpenXml;
using SFB;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEngine;

namespace Custom.Daily.Toolkit
{
    public class DailyToolkitTools : MonoBehaviour
    {
        /// <summary>
        /// 通过脚本复制一个可读的Texture2D
        /// </summary>
        /// <param name="source">源 Texture2D</param>
        /// <returns>可读的 Texture2D</returns>
        public static Texture2D DuplicateTexture(Texture2D source)
        {
            var renderTex = RenderTexture.GetTemporary(
                source.width,
                source.height,
                0,
                RenderTextureFormat.Default,
                RenderTextureReadWrite.Default);

            Graphics.Blit(source, renderTex);
            var previous = RenderTexture.active;
            RenderTexture.active = renderTex;
            var readableText = new Texture2D(source.width, source.height);
            readableText.ReadPixels(new Rect(0, 0, renderTex.width, renderTex.height), 0, 0);
            readableText.Apply();
            RenderTexture.active = previous;
            RenderTexture.ReleaseTemporary(renderTex);
            return readableText;
        }

        /// <summary>
        /// 打开Windows文件系统选择文件
        /// </summary>
        /// <param name="title">窗口标题(默认为 Open File)</param>
        /// <param name="directory">窗口的选择文件(默认为空)</param>
        /// <returns>所打开的所有文件的路径集合</returns>
        public static string[] OpenImageVideoFile(string title = "Open File", string directory = "")
        {
            var extensions = new[]
            {
                new ExtensionFilter("Video Files", "mp4","avi","mkv","wmv"),
                new ExtensionFilter("Image Files", "png", "jpg", "jpeg"),
                new ExtensionFilter("All Files", "*"),
            };
            string[] path = StandaloneFileBrowser.OpenFilePanel(title, directory, extensions, true);
            return path;
        }

        /// <summary>
        /// 读取 Excel 表数据
        /// </summary>
        /// <param name="filePath">Excel 路劲</param>
        /// <param name="sheet">第几张表,默认第一张</param>
        /// <param name="startRow">从第几行开始,默认第一行</param>
        /// <param name="startCol">从第几列开始,默认第一列</param>
        /// <returns>整张表的数据,非法情况下返回 null</returns>
        public static List<List<string>> ReadExcel(string filePath, int sheet = 1, int startRow = 1, int startCol = 1)
        {
            // 打开 Excel 文件
            FileInfo existingFile = new FileInfo(filePath);
            using (ExcelPackage package = new ExcelPackage(existingFile))
            {
                // 获取第一个工作表
                ExcelWorksheet worksheet = package.Workbook.Worksheets[sheet];

                // 获取工作表的总行数和总列数
                int rowCount = worksheet.Dimension.Rows;
                int colCount = worksheet.Dimension.Columns;

                // 遍历每一行每一列，读取内容
                List<List<string>> sheetList = new();
                for (int row = startRow; row <= rowCount; row++)
                {
                    List<string> rowList = new();
                    for (int col = startCol; col <= colCount; col++)
                    {
                        // 获取当前单元格的值
                        var cell = worksheet.Cells[row, col];
                        object cellValue = cell.Value;
                        // 检查单元格是否属于合并区域
                        if (cell.Merge)
                        {
                            // 遍历所有合并区域
                            foreach (var mergedAddress in worksheet.MergedCells)
                            {
                                // 分割出合并区域的起始和结束单元格地址
                                var addresses = mergedAddress.Split(':');
                                var startAddress = addresses[0];
                                var endAddress = addresses[1];

                                // 获取合并区域的起始和结束单元格的行和列
                                var startCell = worksheet.Cells[startAddress];
                                var endCell = worksheet.Cells[endAddress];

                                // 判断当前单元格是否在合并区域范围内
                                if (row >= startCell.Start.Row && row <= endCell.Start.Row &&
                                    col >= startCell.Start.Column && col <= endCell.Start.Column)
                                {
                                    // 从合并区域的起始单元格读取值
                                    var mergeStartCellValue = startCell.Value;
                                    if (mergeStartCellValue != null)
                                    {
                                        rowList.Add(mergeStartCellValue.ToString());
                                    }
                                    else
                                    {
                                        Debug.Log($"[合并类型]单元格内容为空,位置({row},{col})");
                                    }
                                    break; // 找到对应的合并区域后退出循环
                                }
                            }
                        }
                        else
                        {
                            if (cellValue != null)
                            {
                                rowList.Add(cellValue.ToString());
                            }
                            else
                            {
                                Debug.Log($"单元格内容为空,位置({row},{col})");
                            }
                        }
                    }

                    if (rowList.Count > 0)
                    {
                        sheetList.Add(rowList);
                    }
                    else
                    {
                        Debug.Log($"Excel表第 {row} 行没有数据,路径:{filePath}");
                    }
                }

                if (sheetList.Count > 0)
                {
                    return sheetList;
                }
                else
                {
                    Debug.LogError($"Excel表没有数据,路径:{filePath}");
                }
            }
            return new List<List<string>>();
        }

        /// <summary>
        /// 处理横向的情况,例如：["一级围岩","二级标题2","二级标题2","围岩和钻头关系4","xxxx"] 会去掉重复的部分只保留一个
        /// </summary>
        /// <param name="excelData">待处理的数据</param>
        /// <returns>处理后的数据</returns>
        public static List<List<string>> RemoveHorizontalRepeat(List<List<string>> excelData)
        {
            List<List<string>> newExcelData = new();
            if (excelData == null || excelData.Count == 0)
            {
                Debug.LogWarning("excel表数据为空!");
                return newExcelData;
            }

            foreach (var item in excelData)
            {
                newExcelData.Add(item.Distinct().ToList());
            }
            return newExcelData;
        }

        /// <summary>
        /// 从一个字符串中拿到 前缀 后缀 之间的内容组成一个 List<string> 数组
        /// </summary>
        /// <param name="inputStr"></param>
        /// <param name="prefix"></param>
        /// <param name="suffix"></param>
        /// <returns></returns>
        public static List<string> GetStrListByPrefixSuffix(string inputStr, string prefix, string suffix)
        {
            List<string> result = new();
            // 正则表达式匹配 prefix 与 suffix 之间的内容
            MatchCollection matches = Regex.Matches(inputStr, $"{prefix}(.*?){suffix}");
            foreach (Match match in matches)
            {
                result.Add(match.Groups[1].Value); // 获取匹配到的内容
            }

            return result;
        }
    }
}

